package com.northming.daytodo;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.northming.daytodo.conts.ErrorConts;
import com.northming.daytodo.model.Error;
import com.northming.daytodo.model.UserInfo;
import com.northming.daytodo.util.UserUtil;


public class UserSecurityInterceptor  implements HandlerInterceptor{
	
	
	
	
	@Autowired
	private UserUtil userUtil;
	
	
	
		

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		
		boolean validateSession = userUtil.validateSession(request);
		if(!validateSession){
			response.setCharacterEncoding("UTF-8");
			PrintWriter writer = response.getWriter();
			Error error = new Error();
			error.setErrorId(ErrorConts.UNAUTH_ERROR_CODE);
			error.setErrorMes(ErrorConts.UNAUTH_ERROR_MES);
			writer.print("{\"error\":");
			writer.print(JSON.toJSON(error));
			writer.print("}");
			writer.flush();
			writer.close();
			return false;
		}{
			return true;			
		}
	}

}
